﻿# Create your views here.
import time
import random
import string
import datetime

from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required


from django.core.urlresolvers import reverse
from django.utils.functional import curry



from .core.views import ClassViewDecorator
from .core.views import UserIs
from .core.views import BaseView
from .core.views import AjaxView

login_required = curry(login_required,login_url="/")


from .models import VpnUser
from .models import Plan
from .models import Subscription
from .mails import send_password_mail

from .forms import ResetPasswordForm
from .forms import SingInForm
from .forms import SingUpForm
from .forms import HumanForm
from .forms import EditEmailForm
from .forms import EditProfileForm
from .forms import EditPasswordForm
from .forms import EditBillingAddressForm

class AjaxValidationHuman(AjaxView):
    def post(self,request):
        data = {}
        form = HumanForm(request.POST)
        data['status'] = False
        if form.is_valid():
            request.session['is_human'] = True
            data['status'] = True
        return self.responsejson(data=data)


class AjaxResetPassword(AjaxView):
    def post(self,request):
        data = {}
        if request.session.get('is_human', False):
            form = ResetPasswordForm(request.POST)
            if form.is_valid():
                email = form.cleaned_data['email']
                u = User.objects.filter(email=email).get()
                password = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(15))
                u.set_password(password)
                u.save()
                send_password_mail(u.username,email,password)
                data['status'] = True

            else:
                data['status'] = False

        else:
            data['status'] = False
        request.session['is_human'] = False
        time.sleep(1)
        return self.responsejson(data=data)


class AjaxSignIn(AjaxView):
    def post(self,request):
        data = {}
        if request.session.get('is_human', False):
            form = SingInForm(request.POST)
            if form.is_valid():
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                user = authenticate(username=username, password=password)
                login(request, user)
                data['status'] = True
                if not request.POST.get('remember', None):
                    request.session.set_expiry(0)
            else:
                data['status'] = False
                request.session['is_human'] = False
        else:
            data['status'] = False
        time.sleep(1)
        return self.responsejson(data=data)


class AjaxSignUp(AjaxView):
    def post(self,request):
        data = {}
        form = SingUpForm(request.POST)
        if form.is_valid():
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']
            email = form.cleaned_data['email']
            username = form.cleaned_data['username']
            password = form.cleaned_data['password_first']

            user = User.objects.create_user(username=username,email=email,password=password)
            user.last_name = last_name
            user.first_name = first_name
            user.save()
            vuser = VpnUser()
            vuser.name=user
            vuser.save()
            data['status'] = True

        else:
            data['status'] = False
        time.sleep(1)
        return self.responsejson(data=data)





class Index(BaseView):
    def get(self,request):
        if request.user.is_authenticated():
            return self.response(template_file="GeekVPN/Index.html")
        elif request.session.get('is_human', False):
            # request.session['is_human'] = False
            self.response_dict['rpf']=ResetPasswordForm
            self.response_dict['sif']=SingInForm
            self.response_dict['suf']=SingUpForm
            return self.response(template_file="GeekVPN/SignIn.html")
        else:
            # request.session['is_human'] = True
            self.response_dict['hmf']=HumanForm
            return self.response(template_file="GeekVPN/reCaptcha.html")


class AjaxValidationEmail(AjaxView):
    def post(self,request):
        email = request.POST['email']
        if request.user.is_authenticated():
            data =  not User.objects.filter(email=email).exclude(id=request.user.id).exists()
        else:
            data =  not User.objects.filter(email=email).exists()
        return self.responsejson(data=data)


class AjaxValidationEmailForResetPassword(AjaxView):
    def post(self,request):
        email = request.POST['email']
        if request.user.is_authenticated():
            data =  User.objects.filter(email=email).exclude(id=request.user.id).exists()
        else:
            data =  User.objects.filter(email=email).exists()
        return self.responsejson(data=data)

class AjaxValidationUsername(AjaxView):
    def post(self,request):
        username = request.POST['username']
        if request.user.is_authenticated():
            data =  not User.objects.filter(username=username).exclude(id=request.user.id).exists()
        else:
            data =  not User.objects.filter(username=username).exists()
        return self.responsejson(data=data)


@ClassViewDecorator(login_required())
class AjaxEditEmail(AjaxView):
    def post(self,request):
        data = {}
        data['status'] = False
        form = EditEmailForm(request.POST,instance=request.user)
        if form.is_valid():
            form.save()
            data['status'] = True
        return self.responsejson(data=data)

@ClassViewDecorator(login_required())
class AjaxEditPassword(AjaxView):
    def post(self,request):
        data = {}
        data['status'] = False
        form = EditPasswordForm(request.POST,instance=request.user)
        if form.is_valid():
            form.save()
            data['status'] = True
        return self.responsejson(data=data)

@ClassViewDecorator(login_required())
class AjaxEditProfile(AjaxView):
    def post(self,request):
        data = {}
        data['status'] = False
        form = EditProfileForm(request.POST,instance=request.user)
        if form.is_valid():
            form.save()
            data['status'] = True
        return self.responsejson(data=data)


@ClassViewDecorator(login_required())
class AjaxEditBillingAddress(AjaxView):
    def post(self,request):
        data = {}
        data['status'] = False
        form = EditBillingAddressForm(request.POST,instance=request.user.VpnUser)
        if form.is_valid():
            form.save()
            data['status'] = True
        return self.responsejson(data=data)



@ClassViewDecorator(login_required())
class GetTemplate(AjaxView):
    def get(self,request,pagename):
        # self.response_dict['rpf']=ResetPasswordForm
        return self.response(template_file="GeekVPN/Template/" + pagename + ".html")


@ClassViewDecorator(login_required())
class ProfileContent(BaseView):
    def get(self,request):
        return self.response(template_file="GeekVPN/Content/Profile.html")

@ClassViewDecorator(login_required())
class EditProfileContent(BaseView):
    def get(self,request):
        self.response_dict['eef']=EditEmailForm(instance=request.user)
        self.response_dict['epf']=EditProfileForm(instance=request.user)
        self.response_dict['epassf']=EditPasswordForm(instance=request.user)
        self.response_dict['ebaf'] = EditBillingAddressForm(instance=request.user.VpnUser)
        return self.response(template_file="GeekVPN/Content/EditProfile.html")

@ClassViewDecorator(login_required())
class SidebarContent(BaseView):
    def get(self,request):
        return self.response(template_file="GeekVPN/Content/Sidebar.html")


@ClassViewDecorator(login_required())
class PlanContent(BaseView):
    def get(self,request):
        plans = Plan.objects.filter(active=True).all()
        self.response_dict["plans"] = plans
        return self.response(template_file="GeekVPN/Content/Plan.html")

@ClassViewDecorator(login_required())
class AjaxSubPlan(AjaxView):
    def post(self,request):
        data = {}
        data['status'] = False
        try:
            subid = request.POST['plan']
            sub = Subscription.objects.filter(plan_id=subid).filter(user_id=1).latest()
            if sub.plan.registration_cost > request.user.VpnUser.balance:
                data['status'] = False
            else:
                sub.active = True
                cycle_day = sub.plan.cycle
                sub.cycle_start = datetime.datetime.now()
                sub.cycle_finish = datetime.datetime.now() + datetime.timedelta(days=cycle_day)
                sub.user_id = request.user.id
                sub.save()
                request.user.VpnUser.balance = request.user.VpnUser.balance - sub.plan.registration_cost
                request.user.VpnUser.save()
                data['status'] = True
        except:
            pass
        return self.responsejson(data=data)

@ClassViewDecorator(login_required())
class SubscriptionContent(BaseView):
    def get(self,request):
        self.response_dict["subs"] = request.user.subs.all()
        return self.response(template_file="GeekVPN/Content/Subscription.html")

@ClassViewDecorator(login_required())
class AjaxChangeRenewStatus(AjaxView):
    def post(self,request):
        data = {}
        data['status'] = False
        try:
            subid = request.POST['subid']
            status = request.POST['status']
            sub = Subscription.objects.filter(user_id=request.user.id).filter(id=subid).get()
            if status == "true":
                sub.auto_renew = True
                data['status'] = True
            elif status == "false":
                sub.auto_renew = False
                data['status'] = True

            sub.save()
        except:
            pass
        return self.responsejson(data=data)


@ClassViewDecorator(login_required())
class AjaxChangeSub(AjaxView):
    def post(self,request):
        data = {}
        data['status'] = False
        try:
            subid = request.POST['subid']
            sub = Subscription.objects.filter(user_id=request.user.id).filter(id=subid).get()
            username = request.POST['username'].split()[0] + "@" + request.user.username
            password = request.POST['password']
            sub.username = username
            sub.password = password
            sub.save()
            data['status'] = True
        except:
            pass
        return self.responsejson(data=data)





